import("System")
import("System.IO.Ports")
import("Jodell.Tool", "Jodell.Tool")

local Lua_ok = 0
local Lua_Error_Notconnect = -1
local Lua_Error_TimeOut = -2
local Lua_Error_DeviceTypeNotEqual = 3
local Lua_Error_change500 = 4
local Lua_Error_Change501 = 5

local versionRegAddr = 558
local saveRegAddr = 1001
local restoreRegAddr = 1002
local caliEncRegAddr = 1004
local searchZeroRegAddr = 1005

local firmwarePath = "./EPG30-200_APP_AES_0_9_23.bin"
local slaveID = 1
local targetVersion = "0.9.23"

local versionCheckBefore = true -- check version before upgrade



function num2version(major, minor, revision)
    return string.format("%d.%d.%d", major, minor, revision)
end

function readVersion(client, slaveID)
    local ret, data = client:ReadHoldingRegisters(slaveID, versionRegAddr, 3)
    if (ret == 0) then
        local version = num2version((data[0] << 8) + data[1], (data[2] << 8) + data[3], (data[4] << 8) + data[5])
        Info(string.format("设备版本号：%s", version))
        return version
    else
        Info(string.format("无法读取版本号：%d", ret))
        return nil
    end
end

client = Lua_ModbusRtuClient()
client.PortName = "COM16"
client:Connect()

function upgradeTargetFirmware(client, slaveID)
    local deviceVersion = readVersion(client, slaveID)
    local newVersion = deviceVersion

    if (deviceVersion ~= nil) then
        if ((not versionCheckBefore) or (versionCheckBefore and deviceVersion ~= targetVersion)) then
            Info("固件写入中，请耐心等待，大概10s...")
            local res = client:WriteFile(slaveID, 0, firmwarePath)
            if (res == Lua_ok) then
                Info("固件写入成功！")
            else
                Info(string.format("固件写入失败：%d", res))
            end

            Info("等待重启...")
            Delay(2000)
            newVersion = readVersion(client, slaveID)
        end

        if (newVersion ~= nil) then
            if (newVersion == targetVersion) then
                Info(string.format("%d: 升级成功------------------！", slaveID))
            else
                Info(string.format("%d: 升级失败xxxxxxxxxxxxxxxxxx！", slaveID))
            end
        end
    end
end

for i = 1, 12, 1 do
    upgradeTargetFirmware(client, i)
end

client:Disconnect()
